﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DLV.Data.Entities;
using DLV.FrameWork;
using DLV.Library.Utilities;

namespace DLV.BackEnd.Pages
{
    public partial class EditTourPackage : AdminPageBase
    {
        protected bool IsAddService = false;

        private TourPackageInfo _tourPackageInfo = new TourPackageInfo();
        private readonly TourPackageController _tourPackageController = new TourPackageController();

        private List<PriceItemInfo> _priceItemsList = new List<PriceItemInfo>();
        private List<TravelGuideCashInfo> _travelGuideCashList = new List<TravelGuideCashInfo>();


        private List<CommissionInfo> _commissionList=new List<CommissionInfo>();


        private List<VisaPriceInfo> _visaPriceList = new List<VisaPriceInfo>();
        private List<StayInfo> _stayList = new List<StayInfo>();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(Request.QueryString["TourPackageId"]))
                _tourPackageInfo = _tourPackageController.GetTourPackage(int.Parse(Request.QueryString["TourPackageId"]));
            if (!String.IsNullOrEmpty(Request.QueryString["AddService"]))
                IsAddService = true;

            if (Page.IsPostBack) return;

            LoadSchedule();
            LoadAdminUser();
            LoadStatus();
            LoadMartName();

            if (_tourPackageInfo.TourPackageId == -1) return;

            RenderForm();
        }

        protected void lbtSave_Click(object sender, EventArgs e)
        {
            SaveData();
        }
        protected void lbtClose_Click(object sender, EventArgs e)
        {
            RedirectLink();
        }

        private void SaveData()
        {
            _tourPackageInfo.TourPackageName = txtTourPackageName.Text;
            _tourPackageInfo.TourPackageCode = txtTourPackageCode.Text;
            _tourPackageInfo.Description = txtDescription.Text;
            _tourPackageInfo.ScheduleId = int.Parse(ddlSchedule.SelectedValue);
            _tourPackageInfo.MartName = ddlMartName.SelectedValue;
            _tourPackageInfo.Tickets = txtTransports.Value;
            _tourPackageInfo.TicketPrices = GetTotalPriceForItem(txtTransports.Value, "ticket");
            _tourPackageInfo.Restaurant = txtRestaurants.Value;
            _tourPackageInfo.RestaurantPrices = GetTotalPriceForItem(txtRestaurants.Value, "restaurant");
            _tourPackageInfo.Hotels = txtHotels.Value;
            _tourPackageInfo.HotelPrices = GetTotalPriceForItem(txtHotels.Value, "hotel");
            _tourPackageInfo.Visas = txtVisas.Value;
            _tourPackageInfo.VisaPrices = GetTotalPriceForItem(txtVisas.Value, "visa");
            _tourPackageInfo.Insurance = txtInsurances.Value;
            _tourPackageInfo.InsurancePrices = GetTotalPriceForItem(txtInsurances.Value, "insurance");
            _tourPackageInfo.Services = txtServices.Value;
            _tourPackageInfo.ServicePrices = GetTotalPriceForItem(txtServices.Value, "service");
            _tourPackageInfo.TravelGuideCashs = txtTravelGuides.Value;
            _tourPackageInfo.TravelGuideCashPrices = GetTotalPriceForItem(txtTravelGuides.Value, "guide");
            _tourPackageInfo.TotalPrice = _priceItemsList.Sum(p => p.TotalPrice) +
                                          _travelGuideCashList.Sum(p => p.TotalPrice) +
                                          _visaPriceList.Sum(p => p.Price);
            _tourPackageInfo.Status = int.Parse(ddlStatus.SelectedValue);


            _tourPackageInfo.CommissionPrices = GetTotalPriceForItem(txtCommission.Value, "commission");
            _tourPackageInfo.Commissions = txtCommission.Value;

            if (_tourPackageInfo.TourPackageId == -1)
            {
                _tourPackageInfo.CreatedBy = ddlAdminUser.SelectedValue == "-1"
                    ? UserId
                    : int.Parse(ddlAdminUser.SelectedValue);
                _tourPackageInfo.CreatedDate = DateTime.Now;
                _tourPackageController.InsertTourPackage(_tourPackageInfo);
            }
            else
            {
                _tourPackageInfo.UpdatedBy = UserId;
                _tourPackageInfo.UpdatedDate = DateTime.Now;
                _tourPackageController.UpdateTourPackage(_tourPackageInfo);
            }
            RedirectLink();
        }

        private void RenderForm()
        {
            txtTourPackageName.Text = _tourPackageInfo.TourPackageName;
            txtTourPackageCode.Text = _tourPackageInfo.TourPackageCode;
            txtDescription.Text = _tourPackageInfo.Description;
            ddlMartName.SelectedValue = _tourPackageInfo.MartName;
            ddlSchedule.SelectedValue = _tourPackageInfo.ScheduleId.ToString();
            txtTransports.Value = _tourPackageInfo.Tickets;
            txtRestaurants.Value = _tourPackageInfo.Restaurant;
            txtHotels.Value = _tourPackageInfo.Hotels;
            txtVisas.Value = _tourPackageInfo.Visas;
            txtInsurances.Value = _tourPackageInfo.Insurance;
            txtServices.Value = _tourPackageInfo.Services;
            txtTravelGuides.Value = _tourPackageInfo.TravelGuideCashs;
            txtCommission.Value = _tourPackageInfo.Commissions;
        }

        private void RedirectLink()
        {
            Response.Redirect(String.IsNullOrEmpty(Request.QueryString["AddService"])
                ? "/Pages/ListTourPackage.aspx?xml=TourPackage"
                : "/Pages/ListTourPackage.aspx?xml=TourPackageAdd");
        }

        private string ArrayPriceItemId()
        {
            var result = txtTransports.Value;
            result += String.IsNullOrEmpty(txtRestaurants.Value) ? "" : "," + txtRestaurants.Value;
            result += String.IsNullOrEmpty(txtHotels.Value) ? "" : "," + txtHotels.Value;
            result += String.IsNullOrEmpty(txtVisas.Value) ? "" : "," + txtVisas.Value;
            result += String.IsNullOrEmpty(txtInsurances.Value) ? "" : "," + txtInsurances.Value;
            result += String.IsNullOrEmpty(txtServices.Value) ? "" : "," + txtServices.Value;
            result += String.IsNullOrEmpty(txtTravelGuides.Value) ? "" : "," + txtTravelGuides.Value;
            result += String.IsNullOrEmpty(txtCommission.Value) ? "" : "," + txtCommission.Value;
            return result;
        }

        private decimal GetTotalPriceForItem(string itemIds, string itemType)
        {
            if (String.IsNullOrEmpty(itemIds))
                return 0;
            decimal totalPrice;
            var priceItemIds = ArrayPriceItemId();
            priceItemIds = priceItemIds.StartsWith(",") ? priceItemIds.Substring(1) : priceItemIds;
            switch (itemType)
            {
                case "hotel":
                    _stayList = new StayController().ListStayByIds(priceItemIds);
                    totalPrice = _stayList.Sum(stayInfo => stayInfo.TotalPrice);
                    break;
                case "visa":
                    _visaPriceList = new VisaPriceController().ListVisaPriceByIds(priceItemIds);
                    totalPrice = _visaPriceList.Sum(visaPriceInfo => visaPriceInfo.Price);
                    break;
                case "guide":
                    _travelGuideCashList = new TravelGuideCashController().ListTravelGuideCashByIds(priceItemIds);
                    totalPrice = _travelGuideCashList.Sum(travelGuideCashInfo => travelGuideCashInfo.TotalPrice);
                    break;
                case "commission":
                    _commissionList = new CommissionController().ListCommissionByIds(priceItemIds);
                    totalPrice = _commissionList.Sum(commissionInfo => commissionInfo.Price);
                    break;
                default:
                    _priceItemsList = new PriceItemController().ListPriceItemByIds(priceItemIds);
                    totalPrice = _priceItemsList.Where(priceItemInfo => ("," + itemIds + ",").Contains("," + priceItemInfo.PriceItemId + ",")).Sum(priceItemInfo => priceItemInfo.TotalPrice);
                    break;
            }

            return totalPrice;
        }

        private void LoadSchedule()
        {
            ddlSchedule.DataSource =
               new ScheduleController().ListSchedule()
                   .Where(p => p.Status == (int)Globals.DocumentStatus.Use)
                   .OrderBy(p => p.ScheduleName);
            ddlSchedule.DataTextField = "ScheduleName";
            ddlSchedule.DataValueField = "ScheduleId";
            ddlSchedule.DataBind();

            ddlSchedule.Items.Insert(0, new ListItem("--- Chọn lịch trình ---", "-1"));
        }
        private void LoadMartName()
        {
            ddlMartName.Items.Insert(0, new ListItem("--- Chọn thị trường ---", "-1"));
            ddlMartName.Items.Insert(1, new ListItem("Inbound", "Inbound"));
            ddlMartName.Items.Insert(2, new ListItem("Outbound", "Outbound"));
            ddlMartName.Items.Insert(3, new ListItem("Nội địa", "Nội địa"));
        }
        private void LoadAdminUser()
        {
            ddlAdminUser.DataSource = new AdminUserController().ListAdminUser();
            ddlAdminUser.DataTextField = "Username";
            ddlAdminUser.DataValueField = "UserID";
            ddlAdminUser.DataBind();

            ddlAdminUser.Items.Insert(0, new ListItem("--- Chọn người tạo ---", "-1"));
        }
        private void LoadStatus()
        {
            var ds = new DataSet();
            ds.ReadXml(MapPath("~/xml/Status.xml"));
            var dv = ds.Tables["Status"].DefaultView;
            ddlStatus.DataTextField = "Name";
            ddlStatus.DataValueField = "ID";
            ddlStatus.DataSource = dv;
            ddlStatus.DataBind();
        }
    }
}